<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="assets/css/react.css">
    <link rel="stylesheet" href="assets/css/index.css">
    <link rel="stylesheet" href="assets/css/wangEditor.min.css">
</head>

<body>
    <div class="page flex ">
        <section class="side">
            <h4 class="side-add"><a>新建项目</a></h4>
            <ul class="side-add-list">
                <li><input type="text" class="side-add-text" placeholder="请输入项目名称"></li>
                <li>
                    <button class="side-add-push" type="button">提交</button>
                    <button class="side-add-close" type="button">取消</button>
                </li>
            </ul>
            <ul class="side-list">

            </ul>
        </section>
        <section class="ml">
            <h4 class="ml-add"><a>+新建任务</a></h4>
            <ul class="ml-list">
                <!--<li class="list-cell ">
                    <a class="list-a">
                           <span class="list-title">
                            
                               ${value} 
                            </span>
                           <button class='list-nav-a'>+</button>
                    </a>
                    <ul class="list-about">
                        <li>1111</li>
                        <li>字数：1111</li>
                    </ul>
                    <nav class="list-nav">
                        <a class='list-sub'>发布</a>
                        <a class='list-remove'>删除</a>
                        <a class='list-ls'>历史</a>
                    </nav>
                </li>
                <li class="list-cell ">
                    <a class="list-a">
                               <span class="list-title">
                                
                                   ${value} 
                                </span>
                               <button class='list-nav-a'>+</button>
                        </a>
                    <ul class="list-about">
                        <li>1111</li>
                        <li>字数：1111</li>
                    </ul>
                    <nav class="list-nav">
                        <a class='list-sub'>发布</a>
                        <a class='list-remove'>删除</a>
                        <a class='list-ls'>历史</a>
                    </nav>
                </li>
                <li class="list-cell ">
                     <a class="list-a">
                           <span class="list-title">
                            
                               ${value} 
                            </span>
                           <button class='list-nav-a'>+</button>
                    </a>
                    <ul class="list-about">
                        <li>1111</li>
                        <li>字数：1111</li>
                    </ul>
                    <nav class="list-nav">
                        <a class='list-sub'>发布</a>
                        <a class='list-remove'>删除</a>
                        <a class='list-ls'>历史</a>
                    </nav>
                </li>
                <li class="list-cell ">
                    <a class="list-a">
                               <span class="list-title">
                                
                                   ${value} 
                                </span>
                               <button class='list-nav-a'>+</button>
                        </a>
                    <ul class="list-about">
                        <li>1111</li>
                        <li>字数：1111</li>
                    </ul>
                    <nav class="list-nav">
                        <a class='list-sub'>发布</a>
                        <a class='list-remove'>删除</a>
                        <a class='list-ls'>历史</a>
                    </nav>
                </li> -->

            </ul>
        </section>
        <section class="main">
            <div class="top">
                <input class="title" id="title" type="text" placeholder="请输入标题">
                <button class="sub" type="button">保存</button>
            </div>
            <div id="div1" class="toolbar">
            </div>
            <div id="editor" class="text">

            </div>
        </section>
    </div>
    <section class="record">
        <button type="button" class="close">+</button>
        <h3 class="title text-center">本地记录</h3>
        <ul>
            <li><a>
                2017-09-01 11：12：13
            </a></li>
        </ul>

    </section>

    <script src="assets/js/wangEditor.min.js"></script>
    <script src="http://rubaxa.github.io/Sortable/Sortable.js"></script>
    <script>
        //模拟数据 项目
        var pro = [
            {
                title: "项目标题1",
                //任务id
                tesks: ['t0', 't1']
            },
            {
                title: "项目标题3",
                //任务id
                tesks: ['t0', 't1']
            },
            {
                title: "项目标题2",
                //任务id
                tesks: []
            }

        ];

        // 任务
        var dataTesk = {
            "t0": {
                title: "任务名",
                content: "任务内容部分",
                date: ""
            },
            "t1": {
                title: "任务名",
                content: "任务内容部分",
                date: ""
            }
        };
        const record_num = 10;//只存10条
        const record_db = 'jyeditor';//本地db名

        var side_add_input = document.querySelector(".side-add-text");
        var side_add_list = document.querySelector(".side-add-list");
        var side_add = document.querySelector(".side-add-push");
        var side_add_close = document.querySelector(".side-add-close");
        //side 拖拽
        let side_list = document.querySelector(".side .side-list");
        var nowPro = '';//当前选中的项目
        //生成项目

        for (let k in pro) {
            let d = pro[k]
            sideAddLi(d.title, d)
        }

        //本地保存
        function recordDB(id, data) {
            let key = record_db + "_" + id;
            let db = sessionStorage.getItem(key);
            if (data) {
                //保存数据
                let time = new Date().toLocaleTimeString();

                let json = {
                    date: time,
                    data: data
                };
                // 上限
                if ((db.length) <= record_num) {
                    //删除第一条
                    db.shift();
                }
                db.push(json)
            }
            this.remove = function () {
                sessionStorage.removeItem(key);
            }
            return db;
        }

        //新建项目
        document.querySelector(".side-add").addEventListener("click", function () {
            side_add_list.classList.add("active")
            side_add_input.focus();
        });
        //隐藏side add
        side_add_close.addEventListener("click", function () {
            side_add_list.classList.remove("active");
        })
        //添加项目
        function addSidelist() {
            let value = side_add_input.value
            if (!value) {
                return;
            }
            sideAddLi(value)
            getProArr()
            // side_add_close.click();
        }
        side_add.addEventListener("click", addSidelist, false);

        function addSideKeyup(e) {
            if (event.keyCode == 13) side_add.click();
        }
        //输入框获得焦点 添加回车
        side_add_input.addEventListener("focus", function (e) {
            document.addEventListener("keyup", addSideKeyup)
        }, false);

        //解除回车
        function addSideKeyupRemove(e) {
            document.removeEventListener("keyup", addSideKeyup)
        }
        side_add_input.addEventListener("blur", addSideKeyupRemove, false);

        let sortSide = Sortable.create(side_list, {
            handle: ".side-list-a",
            animation: 100,
            filter: '.side-list-remove',
            group: {
                //设置队列名
                name: 'pro',
                put: function (e) {
                    return true;
                },
            },
            onFilter: function (evt) {
                //删除
                let li = evt.item.parentNode.parentNode
                let name = li.querySelector("input") ? li.querySelector("input").value : li.querySelector(".side-list-a").innerHTML;
                if (confirm("是否要删除 " + name)) {
                    li.remove();
                }
            },
            onEnd(e) {
                //拖动结束
                getProArr()
            }
        });

        function getProArr() {
            let lis = sortSide.el.querySelectorAll(".side-list-cell")
            let data = [];
            for (let i = 0; i < lis.length; i++) {
                let v = lis[i].dataset.value
                v = JSON.parse(v)
                data.push(v)
            }
            //反
            data = data.reverse()
            console.log(data)
        }

        function sideAddLi(value, data) {
            let li = document.createElement("li")
            li.classList.add("side-list-cell")
            if (!data) {
                data = {};
                data['title'] = value
                data['tesks'] = []
            }
            //原始数据添加
            let v = JSON.stringify(data);
            li.dataset.value = v;
            li.innerHTML = `
                    <a class="side-list-a">
                            ${value}
                        </a>
                    <ul class="side-list-nav">
                        <li class='side-list-name'>
                            <a class='side-list-sub'>完成</a>
                            <a class='side-list-close'>取消</a>
                            <a class='side-list-ed'>修改名称</a>
                        </li>
                        <li><a class='side-list-remove'>删除项目</a></li>
                    </ul>
                `

            side_list.insertBefore(li, side_list.childNodes[0]);
            //获得 任务
            li.addEventListener("click", openPro, false)
        }



        //点击side li 
        function openPro() {
            if (nowPro === this) return;
            let data = JSON.parse(this.dataset.value)
            let list = data.tesks
            nowPro = this
            //empty()
            let element = ml.el
            while (element.firstChild) element.removeChild(element.firstChild);
            for (let key in list) {
                let k = list[key]
                let d = dataTesk[k]
                if (d) {
                    d["id"] = k
                    setListDom(d.title, d)
                }
            }
            editor.$textElem.attr('contenteditable', false)
        }

        //设置光标位置（obj，n）
        function setCaretPosition(ctrl, pos) {
            if (ctrl.setSelectionRange) {
                ctrl.focus();
                ctrl.setSelectionRange(pos, pos);//设置一个选中的位置
            } else if (ctrl.createTextRange) {
                //ie
                var range = ctrl.createTextRange();
                range.collapse(true);//允许开始和结尾重合
                range.moveEnd('character', pos);
                range.moveStart('character', pos);
                range.select();
            }
        }
        //原始项目名
        var defineName = ''
        //input
        function setName(obj) {
            obj.querySelector(".side-list-name").classList.add('active');
            //获得项目名
            let name = obj.querySelector(".side-list-a").innerHTML;
            //记入原始值
            defineName = name;
            obj.querySelector(".side-list-a").innerHTML = '<input type="text" value=' + name + ' />'
            obj.querySelector("input").focus();
            setCaretPosition(obj.querySelector("input"), name.length)
        }
        //sub pro
        function subName(obj) {
            let name = obj.querySelector("input").value;
            obj.querySelector(".side-list-a").innerHTML = name;
            obj.querySelector(".side-list-name").classList.remove('active');
        }
        //取消 pro
        function closeName(obj) {
            if (obj.querySelector("input")) {
                obj.querySelector(".side-list-a").innerHTML = defineName;
            }
            obj.querySelector(".side-list-name").classList.remove('active');
        }
        // side list nav
        side_list.addEventListener("click", function (e) {
            let li = e.target
            //修改名称
            let obj = li.parentNode.parentNode.parentNode //parent li
            if (li.classList.contains("side-list-ed")) {
                setName(obj)
            } else if (li.classList.contains("side-list-sub")) {
                //完成
                subName(obj)
            } else if (li.classList.contains("side-list-close")) {
                //取消
                closeName(obj)
            } else if (li.classList.contains("side-list-a")) {
                //点击a选中
                let o = li.parentNode
                let active = document.querySelector(".side-list-cell.active")
                if (o !== active) {
                    o.classList.add("active")
                    //init next
                    if (active) {
                        closeName(active);
                        active.classList.remove("active");
                    }
                }
            }
            // e.stopPropagation();//防止点击冒泡
        })

        //新建任务
        let ml_list = document.querySelector(".ml-list");

        var ml = Sortable.create(ml_list, {
            animation: 100,
            handle: ".list-a",
            filter: ".list-nav-a",
            scroll: true,
            group: {
                //设置队列名
                name: 'tesk',
                // //投入设置 
                pull: 'pro',
            },
            //列表元素移到另一个列表容器的回调函数
            onRemove: function (e) {
                //获得项目对象
                let obj = e.item.nextElementSibling
                e.item.remove()
            },
            onMove(e) {
                //拖拽到项目 给目标加 .in
                if (e.to === side_list) {
                    let obj = e.related
                    // let os = document.querySelectorAll(".side-list-cell")
                    // for (let i = 0; i < os.length; i++) {
                    //     let o = os[i]

                    //     if (obj !== o) o.classList.remove("in")
                    // }
                    all(".side-list-cell").removeClass("in", obj)
                    if (obj) obj.classList.add('in')
                }
            },
            onEnd(e) {
                //拖动结束 重置 项目
                all(".side-list-cell").removeClass("in")

            }
        });
        //对象方法
        function all(objs) {

            function obj(objs) {
                //获得对象数组
                this.os = document.querySelectorAll(objs)
                // console.log(thos);
                //remove class of the dom(string,filterObj)
                this.removeClass = function (string, obj) {
                    for (let i = 0; i < this.os.length; i++) {
                        let o = this.os[i]
                        if (!obj || o !== obj) {
                            o.classList.remove(string);
                        }
                    }
                    return this;
                }
                this.click = function (fn) {
                    for (let i = 0; i < this.os.length; i++) {
                        let o = this.os[i]
                        o.addEventListener("click", fn, false)
                    }
                    return this;
                }
            }

            return new obj(objs)
        }

        //list a dom
        function setListDom(value, data) {
            let li = document.createElement("li")
            li.classList.add("list-cell")
            //define title
            let title = "请输入标题"
            if (data) {
                //引索 id
                li.dataset.id = data.id

            } else {
                // 生成新任务
                let id = new Date().toLocaleTimeString()
                //设置id
                li.dataset.id = id
                //获得原数据
                let oldData = nowPro.dataset.value
                let newData = JSON.parse(oldData)
                //define data
                dataTesk[id] = {
                    title: title,
                    content: ""
                }
                newData['tesks'].push(id)
                //添加到 pro 中
                nowPro.dataset.value = JSON.stringify(newData)

            }
            li.innerHTML = ` <a class="list-a">
                               <span class="list-title">
                                
                                  ${value ? value : title} 
                                </span>
                               <button class='list-nav-a'>+</button>
                        </a>
                    <ul class="list-about">
                        <li>字数：0</li>
                    </ul>
                    <nav class="list-nav">
                        <a class='list-sub'>发布</a>
                        <a class='list-remove'>删除</a>
                        <a class='list-ls'>历史</a>
                    </nav>`
            let obj = ml.el
            obj.insertBefore(li, obj.childNodes[0]);
            li.querySelector(".list-a").addEventListener("click", listActive)
        }
        //click新建任务
        document.querySelector(".ml-add a").addEventListener("click", function () {
            if (!nowPro) return alert("请先选择项目");
            setListDom();
        })
        //open tesk
        //当前任务id
        var nowTeskId = '';
        function listActive() {
            let obj = this.parentNode
            if (obj.classList.contains("active")) return;
            all(".list-cell").removeClass("active", obj);
            obj.classList.add("active")
            obj.querySelector(".list-nav-a").addEventListener("click", listNavShow)
            //get data of the tesk
            let id = obj.dataset.id
            let data = dataTesk[id]
            if (data) {
                //get old data 
                document.querySelector("#title").value = data.title
                editor.txt.html(data.content)
            }
            //set tesk id
            nowTeskId = id;
            editor.$textElem.attr('contenteditable', true)

        }
        all(".list-a").click(listActive)

        //list nav
        function listNavHide() {
            let obj = document.querySelector(".list-nav.active")
            if (obj) obj.classList.remove("active");
            document.removeEventListener("click", listNavHide)
        }

        //show nav in list cell 
        function listNavShow(e) {
            let obj = this.parentNode.parentNode
            //更多菜单
            obj.classList.add("active");
            obj.querySelector(".list-nav").classList.add("active");

            //全局隐藏
            document.addEventListener("click", listNavHide)
            e.stopPropagation();

            let target = document.querySelector(".list-cell.active");

            //sub delete 历史
            target.querySelector(".list-sub").addEventListener("click", function (e) {
                e.stopPropagation();

            })

            target.querySelector(".list-remove").addEventListener("click", function (e) {
                console.log(this)
                let id = target.dataset.id;
                let tesk = dataTeskData(id);
                if (!tesk.content || confirm("删除 " + tesk.title + " 将无法恢复")) {

                    let data = DataProData(nowPro);
                    let arr = data.tesks;
                    let index = arr.indexOf(id);
                    let tesks = arr.splice(0, index);
                    let d = { tesks: tesks };

                    DataProData(nowPro, d)
                    target.remove();
                }

                e.stopPropagation();

            })
            target.querySelector(".list-ls").addEventListener("click", function (e) {
                e.stopPropagation();

            })

        }

        //设置获取 tesk 数据
        function DataProData(dom, data) {
            let d;
            d = JSON.parse(dom.dataset.value);
            if (data) {
                for (let key in data) {
                    d[key] = data[key]
                }
                dom.dataset.value = JSON.stringify(d);
            }
            return d
        }

        //设置获取 tesk 数据
        function dataTeskData(id, data) {
            let d = dataTesk[id];
            //set data
            if (data) {
                for (let key in data) {
                    d[key] = data[key]
                }
            }

            return d
        }


        //get data of the editor
        function getEditor() {
            let data = {};
            //tesk id
            data.id = nowTeskId;

            data.title = document.querySelector("#title").value;

            data.content = editor.txt.html();

            return data
        }
        //保存到服务器

        document.querySelector(".sub").addEventListener("click", function () {
            let data = getEditor();
            console.log(data)
        })

        initEditor()
        var editor;
        function initEditor() {
            this.dis = function () {
                editor.option("dis")
            }

            //富文本
            var E = window.wangEditor;
            editor = new E('#div1', '#editor');
            // 或者 var editor = new E( document.getElementById('#editor') )
            editor.customConfig.menus = [
                'head',  // 标题
                'bold',  // 粗体
                // 'italic',  // 斜体
                // 'underline',  // 下划线
                // 'strikeThrough',  // 删除线
                // 'foreColor',  // 文字颜色
                // 'backColor',  // 背景颜色
                // 'link',  // 插入链接
                // 'list',  // 列表
                // 'justify',  // 对齐方式
                'quote',  // 引用
                // 'emoticon',  // 表情
                'image',  // 插入图片
                'table',  // 表格
                'video',  // 插入视频
                'code',  // 插入代码
                'undo',  // 撤销
                'redo'  // 重复
            ];
            editor.create();
            //editor nav
            let ed_nav = document.querySelector(".toolbar")
            let icon = document.createElement('div')
            icon.classList.add("w-e-menu")
            icon.style.zIndex = 100002;
            icon.innerHTML = `<i class='btn-full'>全</i>`
            ed_nav.appendChild(icon);
            document.querySelector(".btn-full").addEventListener('click', function () {
                document.querySelector('.page').classList.toggle('full');
                let value = this.innerHTML
                if (value == '全') {
                    this.innerHTML = '缩'
                } else {
                    this.innerHTML = '全'

                }
            })
            //禁用
            editor.$textElem.attr('contenteditable', false)
        }


        // document.querySelector('#editor .w-e-text-container').style.height = '100%';
    </script>
</body>

</html>